import "ol/ol.css";
import XYZ from "ol/source/XYZ";
import { Feature, Map, View, Collection } from "ol";
import { Tile } from "ol/layer";
import { defaults as defaultControls } from "ol/control";
import Point from "ol/geom/Point";
import LayerVector from "ol/layer/Vector";
import SourceVector from "ol/source/Vector";
import {
  Style,
  Icon,
  Stroke,
  Text,
  Fill,
  Circle as CircleStyle,
} from "ol/style";
import { Translate } from "ol/interaction";
import { LineString } from "ol/geom.js";
import { toLonLat } from "ol/proj";
import WMTS from "ol/source/WMTS.js";
import WMTSTileGrid from "ol/tilegrid/WMTS.js";
import { get as getProjection } from "ol/proj.js";
import { getTopLeft, getWidth } from "ol/extent.js";

// 曲线插件
import smooth from "chaikin-smooth";

let intervals = null;
let map;
export function initMap(target, options = {}, config = { v: true }) {
  const KEY = "cb37cf59d50b321428b932316ab09fcc";

  /**
   * 天地图XYZ瓦片服务图层添加开始
   */
  const tianDiTu = {
    // 矢量
    vector: `https://t${Math.round(
      Math.random() * 7
    )}.tianditu.gov.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=${KEY}`,
    vectorMark:
      "http://t" +
      Math.round(Math.random() * 7) +
      ".tianditu.gov.cn/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=" +
      KEY,
    // 影像
    raster:
      "http://t" +
      Math.round(Math.random() * 7) +
      ".tianditu.gov.cn/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=" +
      KEY,
    rasterMark:
      "http://t" +
      Math.round(Math.random() * 7) +
      ".tianditu.gov.cn/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=" +
      KEY,
    // 地形
    topography:
      "http://t" +
      Math.round(Math.random() * 7) +
      ".tianditu.gov.cn/DataServer?T=ter_w&x={x}&y={y}&l={z}&tk=" +
      KEY,
    topographyMark:
      "http://t" +
      Math.round(Math.random() * 7) +
      ".tianditu.gov.cn/DataServer?T=cta_w&x={x}&y={y}&l={z}&tk=" +
      KEY,
  };
  const tileUrlFunction = function (xyz) {
    const z = xyz[0];
    const x = xyz[1];
    const y = xyz[2];
    return `https://rt1.map.gtimg.com/realtimerender?z=${z}&x=${x}&y=${y}&type=vector&style=0&key=KSMBZ-3SMCV-LTYPU-UPYHY-GI2WF-UWBXB`;
  };
  const crtlayerXYZ = function (
    id,
    url,
    visible,
    tileUrlFunction = function () {}
  ) {
    return new Tile({
      source: new XYZ({
        url,
        crossOrigin: "anonymous",
        tileUrlFunction,
      }),
      properties: {
        layerId: "TileLayers",
      },
      visible,
      id,
    });
  };
  /**
   * 天地图XYZ瓦片服务图层添加结束
   */

  /**
   * 天地图WMTS瓦片服务图层添加开始
   */
  const epsg = "EPSG:4326";
  const projection = getProjection(epsg);
  const projectionExtent = projection.getExtent();
  const size = getWidth(projectionExtent) / 256;
  const length = 17;
  const resolutions = new Array(length);
  const matrixIds = new Array(length);
  for (let i = 0; i < length; i += 1) {
    const pow = Math.pow(2, i);
    resolutions[i] = size / pow;
    matrixIds[i] = i;
  }
  const tianDiTuWMTS = {
    // 矢量
    vector: `http://t0.tianditu.gov.cn/vec_c/wmts?tk=${KEY}`,
    vectorMark: "http://t0.tianditu.gov.cn/cva_c/wmts?tk=" + KEY,
    // 影像
    raster: "http://t0.tianditu.gov.cn/img_c/wmts?tk=" + KEY,
    rasterMark: "http://t0.tianditu.gov.cn/cia_c/wmts?tk=" + KEY,
    // 地形
    topography: "http://t0.tianditu.gov.cn/ter_c/wmts?tk=" + KEY,
    topographyMark: "http://t0.tianditu.gov.cn/cta_c/wmts?tk=" + KEY,
  };
  const crtlayerWMTS = function (id, url, layer, visible) {
    return new Tile({
      source: new WMTS({
        url,
        layer,
        style: "default",
        crossOrigin: "anonymous",
        matrixSet: "c",
        format: "tiles",
        wrapX: true,
        tileGrid: new WMTSTileGrid({
          origin: getTopLeft(projectionExtent),
          resolutions,
          matrixIds,
        }),
      }),
      properties: {
        layerId: "TileLayers",
      },
      visible,
      id,
    });
  };
  /**
   * 天地图WMTS瓦片服务图层添加结束
   */

  /**
   * 高德地图XYZ瓦片服务图层添加开始
   * 参数说明：
      lang=zh_cn设置中文、lang=en设置英文
      scl=1表示含注记，scl=2表示不含注记
      style=6为影像地图，style=7为矢量图，style=8为影像路网
   */

  const gaodeXYZ = {
    // 矢量瓦片服务
    vector:
      "http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scl=2&style=7&x={x}&y={y}&z={z}",
    vectorMark:
      "http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scl=1&style=7&x={x}&y={y}&z={z}",
    // 影像地图
    raster:
      "http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scl=2&style=6&x={x}&y={y}&z={z}",
    rasterMark:
      "http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scl=1&style=8&x={x}&y={y}&z={z}",
    // 影像路网
    topography:
      "http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scl=2&style=8&x={x}&y={y}&z={z}",
    topographyMark:
      "http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scl=1&style=8&x={x}&y={y}&z={z}",
  };

  const gaodeLayerXYZ = function (id, url, visible) {
    return new Tile({
      source: new XYZ({
        title: "高德",
        url,
      }),
      properties: {
        layerId: "TileLayers",
      },
      id,
      visible,
    });
  };
  /**
   * 高德地图XYZ瓦片服务图层添加结束
   */

  map = new Map({
    // 高德地图
    layers: [
      // gaodeLayerXYZ('VECTOR', gaodeXYZ.vector, !!config.v),
      gaodeLayerXYZ("VECTOR", gaodeXYZ.vectorMark, !!config.v),
      // gaodeLayerXYZ('RASTER', gaodeXYZ.raster, !!config.r),
      gaodeLayerXYZ("RASTER", gaodeXYZ.rasterMark, !!config.r),
      // gaodeLayerXYZ('TOPOGRAPHY', gaodeXYZ.topography, !!config.t),
      gaodeLayerXYZ("TOPOGRAPHY", gaodeXYZ.topographyMark, !!config.t),
    ],
    // 天地图WMTS瓦片服务图层添加
    // layers: [
    //   crtlayerWMTS("VECTOR",tianDiTuWMTS.vector, 'vec', !!config.v),
    //   crtlayerWMTS("VECTOR",tianDiTuWMTS.vectorMark, 'cva', !!config.v),
    //   crtlayerWMTS("RASTER",tianDiTuWMTS.raster, 'img', !!config.r),
    //   crtlayerWMTS("RASTER",tianDiTuWMTS.rasterMark, 'cia', !!config.r),
    //   crtlayerWMTS("TOPOGRAPHY",tianDiTuWMTS.topography, 'ter', !!config.t),
    //   crtlayerWMTS("TOPOGRAPHY",tianDiTuWMTS.topographyMark, 'cta', !!config.t),
    // ],
    // 天地图xyz瓦片服务图层添加
    // layers: [
    //   // 矢量
    //   crtlayerXYZ('VECTOR', tianDiTu.vector, !!config.v, tileUrlFunction),
    //   crtlayerXYZ('VECTORMARK', tianDiTu.vectorMark, !!config.v, tileUrlFunction),
    //   // 影像
    //   crtlayerXYZ('RASTER', tianDiTu.raster, !!config.r, tileUrlFunction),
    //   crtlayerXYZ('RASTERMARK', tianDiTu.rasterMark, !!config.r, tileUrlFunction),
    //   // 地形
    //   crtlayerXYZ('TOPOGRAPHY', tianDiTu.topography, !!config.t, tileUrlFunction),
    //   crtlayerXYZ('TOPOGRAPHYMARK', tianDiTu.topographyMark, !!config.t, tileUrlFunction)
    // ],
    target: target,
    view: new View({
      projection: "EPSG:4326",
      center: [110, 30],
      // center: [112.87197876066057, 28.22084712811648],
      // center: [108.90139278683789, 34.29349197118492],
      zoom: 18,
      maxZoom: 18,
      ...options,
    }),
    controls: defaultControls({
      zoom: false,
      rotate: false,
      attribution: false,
    }),
  });
  _eventMapBind();
}

export function getMap() {
  return map;
}

let data = [
  [112.87197876066057, 28.22084712811648],
  [112.8720016491825, 28.225383281160706],
  [112.87314605792562, 28.228450298111515],
  [112.87527465926178, 28.23101377452122],
  [112.87994384801641, 28.232203960351857],
  [112.88353729301525, 28.23128843224413],
];

// 添加标记
export function addMaker(id) {
  const layers = map.getLayers().getArray();
  let layer = layers.find((item) => item.values_.id === id);
  let translate;
  if (layer) {
    layer.getSource().clear();
  } else {
    layer = new LayerVector({
      source: new SourceVector(),
      properties: {
        id: id,
      },
    });
    translate = new Translate({
      layers: [layer],
    });
    map.addLayer(layer);
    map.addInteraction(translate);
  }
  const imgUrl = require("../assets/logo.png");
  for (let index = 0; index < data.length; index++) {
    const element = data[index];

    // 创建矢量对象
    let feature = new Feature({
      geometry: new Point(element),
      properties: [],
    });
    feature.setStyle(
      new Style({
        image: new Icon({
          anchor: [0.5, 1],
          scale: 0.3,
          anchorXUnits: "pixels",
          anchorYUnits: "pixels",
          src: imgUrl,
        }),
      })
    );
    // 添加到之前的创建的layer中去
    layer.getSource().addFeature(feature);
    translate.on("translateend", (e) => {
      console.log(e, "end");
    });
    translate.on("translatestart", (e) => {
      console.log(e, "start");
    });
  }
}

// 添加线
export function addLine(id) {
  const layers = map.getLayers().getArray();
  let layer = layers.find((item) => item.values_.id === id);
  if (layer) {
    layer.getSource().clear();
  } else {
    layer = new LayerVector({
      source: new SourceVector({
        features: "",
      }),
      properties: {
        id: id,
      },
      zIndex: 15,
      // opacity: 1,
      // typeName: 'wkttype'
    });
    map.addLayer(layer);

    // 线的拐弯处为圆滑样式 只有在所有经纬度返回之后才可以
    const smoothened = makeSmooth(data, parseInt(2, 10) || 5);
    // 创建矢量对象
    let feature = new Feature({
      geometry: new LineString(smoothened),
      properties: [],
    });
    feature.setStyle(
      new Style({
        stroke: new Stroke({
          width: 10,
          color: [255, 0, 0, 0.5],
        }),
        // text: new Text({
        //   text: "这是路线",
        //   font: '14px sans-serif',
        //   fill: new Fill({ color: '#000' }),
        //   stroke: new Stroke({ color: '#fff', width: 3 }),
        //   offsetY: -20 // 垂直偏移
        // }),
      })
    );
    // 添加到之前的创建的layer中去
    layer.getSource().addFeature(feature);
  }
}

function _bindMapEvents(layer, translate, lineString) {
  let arr = layer.getSource().getFeatures();

  translate.on("translateend", (e) => {
    for (let index = 0; index < arr.length; index++) {
      const element = arr[index];
      if (element.values_ && element.values_.properties) {
        // 获取几何体的类型名称
        // var type = e.features.getArray()[0].values_.geometry.getType(); // 对于 ol.geom.Point, 返回 'Point'
        // console.log(type,'type');

        if (
          element.values_.properties.id ===
          e.features.getArray()[0].values_.properties.id
        ) {
          data[index] = e.coordinate;
          lineString.setCoordinates(data);
        }
      } else {
        arr.splice(index, 1);
        index--;
      }
    }
  });
}

// 添加轨迹点

let trajectData = [
  [110, 30],
  [110.2, 30],
  [110.4, 30.2],
  [110.8, 30.4],
  [111, 31],
  [111.3, 31],
  [111.6, 31],
  [111.9, 31],
  [112, 31],
  [112.3, 31],
  [112.5, 31],
  [112.8, 31],
  [113, 31],
  [114, 31],
  [115.3, 32],
  [115.5, 32],
  [115.8, 31.8],
  [116, 31.4],
  [116.2, 31.1],
  [116.5, 30.5],
  [115, 30.2],
  [114, 29.8],
  [113, 29.6],
  [112, 29.4],
  [111, 30.2],
  [110, 30.4],
  [109, 30.6],
  [108, 31],
];
export function addTrajectory(id) {
  const layers = map.getLayers().getArray();
  let layer = layers.find((item) => item.values_.id === id);

  if (layer) {
    layer.getSource().clear();
  } else {
    layer = new LayerVector({
      source: new SourceVector({
        features: "",
      }),
      properties: {
        id: id,
      },
    });
    map.addLayer(layer);
  }

  let imgUrl = require("../assets/111.png");
  let iconFeature = new Feature({
    geometry: new Point([110, 30]),
  });

  let icon = new Icon({
    anchor: [120, 1],
    scale: 0.2,
    anchorXUnits: "pixels",
    anchorYUnits: "pixels",
    src: imgUrl,
  });
  iconFeature.setStyle(
    new Style({
      image: icon,
    })
  );

  // 添加到之前的创建的layer中去
  layer.getSource().addFeature(iconFeature);

  let i = 0;
  intervals = setInterval(() => {
    if (trajectData[i + 1]) {
      iconFeature.setGeometry(new Point(trajectData[i + 1]));
      let arc = 0;
      if (
        (trajectData[i + 1][0] - trajectData[i][0] >= 0 &&
          trajectData[i + 1][1] - trajectData[i][1] >= 0) ||
        (trajectData[i + 1][0] - trajectData[i][0] < 0 &&
          trajectData[i + 1][1] - trajectData[i][1] > 0)
      ) {
        arc = Math.atan(
          (trajectData[i + 1][0] - trajectData[i][0]) /
            (trajectData[i + 1][1] - trajectData[i][1])
        );
      } else if (
        (trajectData[i + 1][0] - trajectData[i][0] > 0 &&
          trajectData[i + 1][1] - trajectData[i][1] < 0) ||
        (trajectData[i + 1][0] - trajectData[i][0] < 0 &&
          trajectData[i + 1][1] - trajectData[i][1] < 0)
      ) {
        arc =
          Math.PI +
          Math.atan(
            (trajectData[i + 1][0] - trajectData[i][0]) /
              (trajectData[i + 1][1] - trajectData[i][1])
          );
      }

      icon.setRotation(arc); //设置航向角（与正北的夹角）

      // 创建矢量对象
      let feature = new Feature({
        geometry: new LineString([trajectData[i], trajectData[i + 1]]),
      });
      feature.setStyle(
        new Style({
          stroke: new Stroke({
            color: [255, 0, 0, 0.5],
            width: 4,
          }),
        })
      );
      layer.getSource().addFeature(feature);
      i++;
    } else {
      clearInterval(intervals);
      intervals = null;
    }
  }, 2000);
}

// 使用npm包chaikin-smooth，它实现了Chaikins算法来平滑绘制的线条。首先在地图上画画。完成绘图后，特征的几何图形将按照形状元素的配置进行平滑。
function makeSmooth(path, numIterations) {
  numIterations = Math.min(Math.max(numIterations, 1), 10);
  while (numIterations > 0) {
    path = smooth(path);
    numIterations--;
  }
  return path;
}

// 鼠标点击事件
function _eventMapBind() {
  map.on("click", (evt) => {
    // console.log(evt.coordinate,toLonLat(evt.coordinate),map.getView().getZoom());
  });
}

// 清除定时器
export function clearIntervalEvents() {
  if (intervals) {
    clearInterval(intervals);
    intervals = null;
  }
}

/**
 * 添加类似知识图谱
 * 需要两个图层来实现
 * 1、线图层  不拖动
 * 2、点图层 需要拖动
 */
// 线图层
export function addKnowledgeGraphLinePoint(id) {
  const layers = map.getLayers().getArray();
  let layer = layers.find((item) => item.values_.id === id);
  if (layer) {
    layer.getSource().clear();
  } else {
    layer = new LayerVector({
      source: new SourceVector({
        features: "",
      }),
      properties: {
        id: id,
      },
      zIndex: 15,
    });
    map.addLayer(layer);

    // 创建矢量对象
    var lineString = new LineString(data);
    var lineFeature = new Feature({ geometry: lineString });
    // 添加到之前的创建的layer中去
    layer.getSource().addFeature(lineFeature);
  }
  addKnowledgeGrapPoint("KnowledgeGrapPoint", lineString);
}
// 点图层
function addKnowledgeGrapPoint(id, lineString) {
  const layers = map.getLayers().getArray();
  let layer = layers.find((item) => item.values_.id === id);
  let translate;
  if (layer) {
    layer.getSource().clear();
  } else {
    layer = new LayerVector({
      source: new SourceVector(),
      properties: {
        id: id,
      },
    });
    translate = new Translate({
      layers: [layer],
    });
    map.addLayer(layer);
    map.addInteraction(translate);
  }
  for (let index = 0; index < data.length; index++) {
    const element = data[index];

    // 创建矢量对象
    let feature = new Feature({
      geometry: new Point(element),
      properties: { id: "points" + index },
    });
    // 添加到之前的创建的layer中去
    layer.getSource().addFeature(feature);

    _bindMapEvents(layer, translate, lineString);
  }
}

// 添加点位类似波纹效果闪动的marker
export function addRippleFlashingPoint(id) {
  const layers = map.getLayers().getArray();
  let layer = layers.find((item) => item.values_.id === id);

  if (layer) {
    layer.getSource().clear();
  } else {
    layer = new LayerVector({
      source: new SourceVector({
        features: "",
      }),
      properties: {
        id: id,
      },
    });
    map.addLayer(layer);
  }

  // 创建固定中心点
  const centerFeature = new Feature({
    geometry: new Point([112.87197876066057, 28.22084712811648]),
    id: id + "_center",
  });
  centerFeature.setStyle(
    new Style({
      image: new CircleStyle({
        radius: 4,
        fill: new Fill({ color: "#f00" }),
        stroke: null,
      }),
    })
  );

  // 创建波纹特征
  const rippleFeature = new Feature({
    geometry: new Point([112.87197876066057, 28.22084712811648]),
    id: id + "_ripple",
  });

  let radius = 4; // radius一定要放在监听事件外面
  let opacity = 1; // 波纹的透明度

  map.on("postcompose", (event) => {
    const rippleFeatures = layer
      .getSource()
      .getFeatures()
      .filter((item) => item.values_.id.includes("_ripple"));
    opacity = (20 - radius) * (1 / 20); // 不透明度 radius为0时，不透明；radius为25时，透明
    rippleFeatures.forEach((item) => {
      item.setStyle(
        new Style({
          image: new CircleStyle({
            radius: radius,
            fill: null,
            stroke: new Stroke({
              color: "rgba(255, 0, 0, " + opacity + ")", // 通过rgba控制波纹的产生和消失
              width: 2 + opacity,
            }),
          }),
        })
      );
    });
    radius = radius + 0.3;
    radius = radius >= 20 ? 4 : radius;
  });
  layer.getSource().addFeature(centerFeature);
  layer.getSource().addFeature(rippleFeature);
  map.render(); // 触发地图绑定的postcompose事件
}

// 添加点位 最后一个点闪动
export function addLastPointFlashing(id) {
  const layers = map.getLayers().getArray();
  let layer = layers.find((item) => item.values_.id === id);
  if (layer) {
    layer.getSource().clear();
  } else {
    layer = new LayerVector({
      source: new SourceVector({
        features: "",
      }),
      properties: {
        id: id,
      },
      zIndex: 15,
      // opacity: 1,
      // typeName: 'wkttype'
    });
    map.addLayer(layer);

    // 创建矢量线对象
    let featureLine = new Feature({
      geometry: new LineString(data),
      properties: [],
    });
    featureLine.setStyle(
      new Style({
        stroke: new Stroke({
          width: 2,
          color: "#F53F3F",
          lineDash: [5, 5],
        }),
      })
    );
    // 创建矢量点对象
    for (let index = 0; index < data.length; index++) {
      const element = data[index];

      // 第一个点（实心圆）
      let featurePoint = new Feature({
        geometry: new Point(element),
        properties: [],
      });
      featurePoint.setStyle(
        new Style({
          image: new CircleStyle({
            radius: 8,
            fill: new Fill({ color: "#F53F3F" }),
            stroke: null,
          }),
          text: new Text({
            text: "这是路线",
            font: "14px sans-serif",
            fill: new Fill({ color: "#000" }),
            stroke: new Stroke({ color: "#fff", width: 3 }),
            offsetY: 25, // 垂直偏移
          }),
        })
      );

      // 第二个点（空心波纹圆）
      let featurePoint1 = new Feature({
        geometry: new Point(element),
        properties: [],
        id: id + "_ripple",
      });
      featurePoint1.setStyle(
        // 修正为featurePoint1
        new Style({
          image: new CircleStyle({
            radius: 11,
            stroke: new Stroke({
              color: "rgba(245,63,63,0.4)",
              width: 11,
            }),
            fill: null, // 明确设置为null避免干扰
          }),
        })
      );

      if (index === data.length - 1) {
        let radius = 11; // radius一定要放在监听事件外面
        let opacity = 0.4; // 波纹的透明度

        map.on("postcompose", (event) => {
          featurePoint1.setStyle(
            new Style({
              image: new CircleStyle({
                radius: radius,
                fill: null,
                stroke: new Stroke({
                  color: "rgba(255, 0, 0, " + opacity + ")", // 通过rgba控制波纹的产生和消失
                  width: 2 + opacity,
                }),
              }),
            })
          );
          radius = radius + 0.3;
          radius = radius >= 20 ? 4 : radius;
        });
      }

      // 先添加大圆（波纹效果），再添加小圆（中心点）
      layer.getSource().addFeature(featurePoint1);
      layer.getSource().addFeature(featurePoint);
    }
    // 添加到之前的创建的layer中去
    layer.getSource().addFeature(featureLine);
  }
}

let trajectDatas = [
  [110, 30],
  [110.2, 30],
  [110.4, 30.2],
];
// 使用圆点标记实现实时轨迹，并且在每个点上添加文字
export function addRealTimeTrackText(id) {
  const layers = map.getLayers().getArray();
  let layer = layers.find((item) => item.values_.id === id);

  if (layer) {
    layer.getSource().clear();
  } else {
    layer = new LayerVector({
      source: new SourceVector(),
      properties: { id: id },
    });
    map.addLayer(layer);
  }

  // 预定义样式
  const pointStyle = new Style({
    image: new CircleStyle({
      radius: 8,
      fill: new Fill({ color: "#F53F3F" }),
      stroke: null,
    }),
    text: new Text({
      font: "14px sans-serif",
      fill: new Fill({ color: "#000" }),
      stroke: new Stroke({ color: "#fff", width: 3 }),
      offsetY: 25,
    }),
  });

  const pointStyle1 = new Style({
    image: new CircleStyle({
      radius: 11,
      stroke: new Stroke({
        color: "rgba(245,63,63,0.4)",
        width: 11,
      }),
      fill: null, // 明确设置为null避免干扰
    }),
  });

  let i = 0;
  intervals = setInterval(() => {
    if (i < trajectDatas.length) {
      // 添加点位标记
      const pointFeature = new Feature({
        geometry: new Point(trajectDatas[i]),
        properties: { name: `点位${i + 1}` },
      });
      const currentStyle = pointStyle.clone();
      currentStyle.getText().setText(pointFeature.get("properties").name);
      pointFeature.setStyle(currentStyle);

      const pointFeature1 = new Feature({
        geometry: new Point(trajectDatas[i]),
      });
      const currentStyle1 = pointStyle1.clone();
      pointFeature1.setStyle(currentStyle1);

      layer.getSource().addFeature(pointFeature1);
      layer.getSource().addFeature(pointFeature);

      // 添加连线（非第一个点时）
      if (i > 0) {
        const lineFeature = new Feature({
          geometry: new LineString([trajectDatas[i - 1], trajectDatas[i]]),
        });
        lineFeature.setStyle(
          new Style({
            stroke: new Stroke({
              width: 2,
              color: "#F53F3F",
              lineDash: [5, 5],
            }),
          })
        );
        layer.getSource().addFeature(lineFeature);
      }
      i++;
      if(i === trajectDatas.length) {
        let radius = 11; // radius一定要放在监听事件外面
        let opacity = 0.4; // 波纹的透明度
        map.on("postcompose", (event) => {
          pointFeature1.setStyle(
            new Style({
              image: new CircleStyle({
                radius: radius,
                fill: null,
                stroke: new Stroke({
                  color: "rgba(255, 0, 0, " + opacity + ")", // 通过rgba控制波纹的产生和消失
                  width: 2 + opacity,
                }),
              }),
            })
          )
          radius = radius + 0.3;
          radius = radius >= 20 ? 4 : radius;
        })
      }
    } else {
      clearInterval(intervals);
      intervals = null;
    }
  }, 2000);
}

// 根据图层ID清除对应图层
export function clearLayer(id) {
  if (intervals) {
    clearInterval(intervals);
  }
  const layers = map.getLayers().getArray();
  const layer = layers.filter((item, index) => item.values_.id === id);
  layer.forEach((item) => {
    map.removeLayer(item);
  });
}
